<?php
/**
 * 签名授权
 */

namespace app\api\model;

use think\Model;
use think\Cache;

class Auth extends Base
{
    /**
    * 签名
    * @param param  参数数组
    * @return array|null
    */
    public function _sign($param){
        $tmp = $param;
        ksort($tmp);
        $str = '';
        foreach($tmp as $k=>$v){
            if($v === 0 || !empty($v)){
                $str .= $k.'='.$v.'&';
            }
            
        }
        $app_key = config('app_key');
        
        $sign = $str.'key='.$app_key;
        $sign = strtoupper(MD5($sign));
        return $sign;
    }
    
    /**
    * 签名验证
    * @param param array 要验证的参数数组
    * @param mid int 用户id
    * @param api_cycle int 接口请求生命周期
    */
    public function _checkSign($param, $mid, $api_cycle){
        $tmp = $param;
        if(empty($tmp['time_stamp'])){
            $this->error = '请求时间不能为空';
            return false;
        }
        $time_stamp = $tmp['time_stamp'];
 
        if((time()-$time_stamp) > $api_cycle){
            $this->error = '该请求已失效';
            return false;
        }
        if(empty($tmp['sign'])){
            $this->error = '签名不能为空';
            return false;
        }
        $clien_sign = $param['sign'];
        unset($tmp['sign']);
        $service_sign = $this->_sign($tmp);
        
        if(strcmp($clien_sign, $service_sign)){
            $this->error = '签名不一致';
            return false;
        }
        
        $cache_sign = Cache::get($clien_sign);
        if(!empty($cache_sign)){
            $this->error = '该签名已失效';
            //Cache::rm('sign'.$mid); 
            return false;
        }
        Cache::set($clien_sign, $clien_sign);
        
        return true;
    }
    
}